<template>
    <div class="home full" @dragover.prevent @drop.prevent="handleDrop">
        <div class="full" id="allmap"></div>
        
        <ul class="tool">
            <li class="tool-kind">
                <i class="el-icon-s-management"></i>
                路书
                <i class="el-icon-arrow-down"></i>
                <ul class="tool-list">
                    <li class="tool-item" @click="luluSu(map)">
                        <i class="el-icon-position"></i>
                        创建
                    </li>
                    <li class="tool-item" @click="lushu.start()">
                        <i class="el-icon-position"></i>
                        开始
                    </li>
                    <li class="tool-item" @click="lushu.stop()">
                        <i class="el-icon-position"></i>
                        停止
                    </li>
                    <li class="tool-item" @click="lushu.pause()">
                        <i class="el-icon-position"></i>
                        暂停
                    </li>
                </ul>
            </li>
            <li class="tool-kind" @click="handleClearOverlays">
                <i class="el-icon-s-management"></i>
                清除覆盖物
                <!-- <i class="el-icon-arrow-down"></i> -->
            </li>
            <li class="tool-kind" @click="isShowBall=false">
                <i class="el-icon-s-management"></i>
                取消闪烁
                <!-- <i class="el-icon-arrow-down"></i> -->
            </li>
            <li class="tool-kind" @click="handleClearOverlays">
                <i class="el-icon-s-management"></i>
                绘制设置
                <i class="el-icon-arrow-down"></i>
                <ul class="tool-list">
                    <li class="tool-item">
                        <el-color-picker v-model="styleOptions.strokeColor" size="mini" @change="handleColorChange"></el-color-picker>
                        <span class="label-title">边线颜色</span>
                    </li>
                    <li class="tool-item">
                        <el-color-picker v-model="styleOptions.fillColor" size="mini" @change="handleColorChange"></el-color-picker>
                        <span class="label-title">填充颜色</span>
                    </li>
                    <li class="tool-item">
                        <!-- <el-color-picker v-model="styleOptions.fillOpacity" size="mini"></el-color-picker> -->
                        <el-popover
                            placement="right"
                            width="200"
                            trigger="click">
                                <el-slider
                                 @change="handleColorChange"
                                v-model="styleOptions.fillOpacity"
                                :max="1"
                                :step="0.1"
                                show-stops>
                                </el-slider>
                            <!-- <el-button slot="reference">click 激活</el-button> -->
                            <span slot="reference" class="label-title">透明度设置</span>
                        </el-popover>
                    </li>
                </ul>
            </li>
            <li class="tool-kind">
                <i class="el-icon-s-management"></i>
                工具箱
                <i class="el-icon-arrow-down"></i>
                <ul class="tool-list">
                    <li class="tool-item" @click="handleDistance">
                        <i class="el-icon-position"></i>
                        测距
                    </li>
                    <li class="tool-item" @click="handleAddGroundOverlay">
                        <i class="el-icon-position"></i>
                        添加图层
                    </li>
                    <li class="tool-item" @click="handleRemoveGroundOverlay">
                        <i class="el-icon-position"></i>
                        删除图层
                    </li>
                    <li class="tool-item" @click="handleRemoveGroundOverlay">
                        <i class="el-icon-position"></i>
                       <el-popover
                            placement="right"
                            width="200"
                            v-model="themeVisible"
                            trigger="click">
                               <el-radio-group v-model="theme" @change="handleThemeChange">
                                    <el-radio label="normal">默认</el-radio>
                                    <el-radio label="dark">深色</el-radio>
                                    <el-radio label="light">浅色</el-radio>
                                </el-radio-group>
                            <!-- <el-button slot="reference">click 激活</el-button> -->
                            <span slot="reference" class="label-title">地图样式</span>
                        </el-popover>
                    </li>
                    <!-- <li class="tool-item" @click="handleAddStyle">
                        <i class="el-icon-position"></i>
                        添加样式
                    </li>
                    <li class="tool-item" @click="handleRemoveStyle">
                        <i class="el-icon-position"></i>
                        取消样式
                    </li> -->
                    <li class="tool-item" @click="heatmapOverlay.show()">
                        <i class="el-icon-position"></i>
                        显示热力图
                    </li>
                    <li class="tool-item" @click="heatmapOverlay.hide()">
                        <i class="el-icon-position"></i>
                        关闭热力图
                    </li>
                </ul>
            </li>
        </ul>

        <div class="search-wrap">
            <el-input placeholder="请输入内容" v-model="key" class="input-with-select">
                <el-button slot="prepend" @click="handleGetRoad">路线</el-button>
                <el-button slot="append" icon="el-icon-search" @click="handleLocalSearch"></el-button>
            </el-input>
            <!-- <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div> -->
            <div v-if="isRoad">
                <el-input v-model="start" placeholder="请输入起点" @focus="handleFocus('start')"></el-input>
                <el-input v-model="end" placeholder="请输入终点" @focus="handleFocus('end')"></el-input>
                <el-button @click="handleSave">救援</el-button>
                <!-- <div id="r-result"></div> -->
            </div>
        </div>
        
        <aside>
            <ul>
                <li @click="handleMenuClick('0')">
                    <div class="a-title"> <span>添加标识</span>  <i class="el-icon-arrow-down"></i> </div>
                    <ul class="sub-item-wrap" :class="{active: activeObj['0']}">
                        <li class="sub-item" v-for="(item, index) in imgList" :key="index" @click.stop.prevent="handleAddMark(index)">
                            <img draggable :src="item.url" alt="车队">
                            <span class="label-name">{{item.text}}</span>
                        </li>
                    </ul>
                </li>
            </ul>
        </aside>

        <div v-show="isShowBall" class="ball-scale" :style="ballStyle" data-loader="ball-scale"></div>

    </div>
</template>

<script>
import mapStyle from 'common/mapStyle.json'
import myCar from 'assets/img/car.png'
import si_huan from 'assets/img/si-huan.png'

// 控件
import {
    bottom_left_control,
    top_right_navigation,
} from 'common/control.js'
// 信息窗口html
import { 
    infoWindow,
    infoWindow2,
} from "common/infoWindow.js";
// 图标
import {
    myIcons
} from 'common/icon.js'
// 图列表
import { imgList } from "common/img.js";
//
import {hotPoints} from 'common/hotPoints.js' 


let infoWin = new BMap.InfoWindow(infoWindow, {offset: new BMap.Size(0, -10)});
let infoWin2 = new BMap.InfoWindow(infoWindow2, {offset: new BMap.Size(0, -10)});
var curMkr = null; // 记录当前添加的Mkr
let currentSelect = ''
export default {
    name: 'home',
    data() {
        return {
            map: null,
            myDis: null, // 测距
            drawingManager: null,
            overlays: [], // 鼠标绘制的覆盖物
            geoc: null, // 地址解析
            mkrTool: null, // 标注工具

            styleOptions: {
                strokeColor:"#ff0000",    //边线颜色。
                fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 3,       //边线的宽度，以像素为单位。
                strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
                fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                strokeStyle: 'solid' //边线的样式，solid或dashed。
            },

            isRoad: false,
            key: '',
            start: '',
            end: '',
            imgList: imgList,
            searchInfoWindow: null,
            isShowBall: false,
            ballStyle: {
                left: '0',
                top: '0',
            },
            lishu: null,
            transit: null, // 驾车
            driving: null,
            local: null,
            groundOverlay: null,
            activeObj: {
                
            },
            theme: 'dark',
            themeVisible: false,
            heatmapOverlay: null,
        }
    },
    components: {
        
    },
    methods: {
        initMap ()  {
            let map = new BMap.Map("allmap")
            this.map = map
            this.geoc = new BMap.Geocoder()
            this.initTool(map)
            this.initMouseTool(map)
            this.initMarkerTool(map)
            this.initSearchInfo(map)
            this.initDriving(map)
            this.initLocalSearch(map)
            // this.luluSu(map)
            this.initGroundOverlay()
            map.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
            map.enableScrollWheelZoom(true)
             map.setMapStyle({style:'dark'})
            // map.setMapStyleV2({styleJson:mapStyle}) // 版本3支持
            map.addControl(bottom_left_control)
            map.addControl(top_right_navigation)
            map.addEventListener('click', this.mapClick)
            var ctrl = new BMapLib.TrafficControl({
                showPanel: false //是否显示路况提示面板
            });      
            map.addControl(ctrl);
            ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
            this.initHotMap(map)
        },
        handleThemeChange (e) {
            this.map.setMapStyle({style:e})
            this.themeVisible = false
        },
        handleRemoveStyle () {
            this.map.setMapStyleV2({styleJson:[]})
        },
        handleAddStyle () {
            this.map.setMapStyleV2({styleJson:mapStyle})
        },
        mapClick (e) {
            let current = currentSelect
            console.log(e)
            var pt = e.point;
		this.geoc.getLocation(pt, (rs) => {
            var addComp = rs.addressComponents;
            console.log(rs)
            if (current) {
                if (current === 'start') {
                    this.start = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber
                } else if (current === 'end') {
                    this.end = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber
                }
            }
			// console.log(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
		})
        },
        // 初始化工具
        initTool (map) {
            let myDis = new BMapLib.DistanceTool(map)
            this.myDis = myDis
        },
        initHotMap(map) {
          var  heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20});
            map.addOverlay(heatmapOverlay);
            heatmapOverlay.setDataSet({data:hotPoints,max:100});
            this.heatmapOverlay = heatmapOverlay
            heatmapOverlay.hide()
        },
        // 标注工具
        initMarkerTool (map) {
            let self = this
           var removeMarker = function(e,ee,marker){
                self.map.removeOverlay(marker);
                self.isShowBall = false
            }
            var mkrTool = new BMapLib.MarkerTool(map, {autoClose: true, followText: '添加'});
            mkrTool.addEventListener("markend", function(evt){ 
                var mkr = evt.marker;
                mkr.enableDragging()
                mkr.openInfoWindow(infoWin);
                console.log(evt)
                var poi = evt.marker.point
                self.geoc.getLocation(poi, (rs) => {
                    var addComp = rs.addressComponents;
                    console.log(rs)
                    document.getElementById("txtAddr").value = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber

                })
                curMkr = mkr;

                // 右键删除
                var markerMenu=new BMap.ContextMenu();
    markerMenu.addItem(new BMap.MenuItem('删除',removeMarker.bind(mkr)));
    mkr.addContextMenu(markerMenu);

                mkr.addEventListener('click', function(e) {
                    curMkr = this
                    console.log(e)
                    let obj ={
                        left: e.pixel.x+'px',
                        top: e.pixel.y+'px'
                    }
                    self.ballStyle = obj
                    // self.isShowBall = true
                    this.openInfoWindow(infoWin)
                    
                    var poi = e.point
                    self.geoc.getLocation(poi, (rs) => {
                        var addComp = rs.addressComponents;
                        document.getElementById("txtAddr").value = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber

                    })
                })
                mkr.addEventListener('dblclick', function() {
                    curMkr = this
                    //  self.searchInfoWindow.open(this)
                    this.openInfoWindow(infoWin2)
                })
            });
            this.mkrTool = mkrTool
        },
        // 信息搜索
        initSearchInfo (map) {
            var content = '内容'
            var searchInfoWindow = null;
            searchInfoWindow = new BMapLib.SearchInfoWindow(map, content, {
                    title  : "搜索信息",      //标题
                    width  : 320,             //宽度
                    height : 105,              //高度
                    panel  : "panel",         //检索结果面板
                    enableAutoPan : true,     //自动平移
                    searchTypes   :[
                        BMAPLIB_TAB_SEARCH,   //周边检索
                        BMAPLIB_TAB_TO_HERE,  //到这里去
                        BMAPLIB_TAB_FROM_HERE //从这里出发
                    ]
            })
            this.searchInfoWindow = searchInfoWindow
        },
        initMouseTool (map) {
            //实例化鼠标绘制工具
            let drawingManager = new BMapLib.DrawingManager(map, {
                isOpen: false, //是否开启绘制模式
                enableDrawingTool: true, //是否显示工具栏
                drawingToolOptions: {
                    anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                    offset: new BMap.Size(80, 5), //偏离值
                },
                circleOptions: this.styleOptions, //圆的样式
                polylineOptions: this.styleOptions, //线的样式
                polygonOptions: this.styleOptions, //多边形的样式
                rectangleOptions: this.styleOptions //矩形的样式
            })
            this.drawingManager = drawingManager
            drawingManager.addEventListener('overlaycomplete', this.overlaycomplete)
        },
        overlaycomplete (e) {
            this.overlays.push(e.overlay)
            e.overlay.addEventListener("click", this.attribute)
        },
        attribute (e) {
            this.map.removeOverlay(e.currentTarget)
        },
        handleClearOverlays () {
            for(var i = 0; i < this.overlays.length; i++){
                this.map.removeOverlay(this.overlays[i]);
            }
            this.overlays.length = 0
        },
        // 测距
        handleDistance () {
            this.myDis.open()
        },
        // 设置鼠标绘制颜色
        handleColorChange () {
            this.initMouseTool(this.map)
        },
        // 线路
        handleGetRoad () {
            this.isRoad = !this.isRoad
            document.getElementById('r-result').innerHTML = ''
        },
        handleFocus (poi) {
            currentSelect = poi
        },
        handleDrop (e) {
            console.log(e)
        },
        handleAddMark (index) {
            this.mkrTool.open()
            this.mkrTool.setIcon(myIcons[index])
        },
        encodeHTML(a){
            return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
        },
        initGlobalMethods () {
         //提交数据
         let self = this
            function fnOK(){
                var name = self.encodeHTML(document.getElementById("txtName").value);
                var tel = self.encodeHTML(document.getElementById("txtTel").value);
                var addr = self.encodeHTML(document.getElementById("txtAddr").value);
                var desc = self.encodeHTML(document.getElementById("areaDesc").value);

                // if(!name || !tel || !addr){
                //     alert("星号字段必须填写");    
                //     return;
                // }

                if(curMkr){
                    //设置label
                    var lbl = new BMap.Label(name, {offset: new BMap.Size(9, -19)});
                    lbl.setStyle({border: "solid 1px gray"});
                    self.map.removeOverlay(curMkr.getLabel())
                    curMkr.setLabel(lbl);
                    
                    //设置title
                    var title = "电话: " + tel + "\n\r" + "地址: " +addr + "\n\r" + "描述: " + desc;
                    curMkr.setTitle(title);        
                }
                if(infoWin.isOpen()){
                    self.map.closeInfoWindow();
                }

                //在此用户可将数据提交到后台数据库中
            }
            function fnOK1(){
                var name = self.encodeHTML(document.getElementById("labName").value);

                // if(!name || !tel || !addr){
                //     alert("星号字段必须填写");    
                //     return;
                // }

                if(curMkr){
                    //设置label
                    var lbl = new BMap.Label(name, {offset: new BMap.Size(9, -19)});
                    lbl.setStyle({border: "solid 1px gray"});
                    console.log(curMkr.getLabel())
                    self.map.removeOverlay(curMkr.getLabel())
                    curMkr.setLabel(lbl);
                    
                    //设置title
                    // var title = "电话: " + tel + "\n\r" + "地址: " +addr + "\n\r" + "描述: " + desc;
                    // curMkr.setTitle(title);        
                }
                if(infoWin2.isOpen()){
                    self.map.closeInfoWindow();
                }

                //在此用户可将数据提交到后台数据库中
            }

            //输入校验

            //重填数据
            function fnClear(){
                document.getElementById("txtName").value = "";
                document.getElementById("txtTel").value = "";
                document.getElementById("txtAddr").value = "";
                document.getElementById("areaDesc").value = "";
            }
            window.fnOK = fnOK
            window.fnOK1 = fnOK1
            window.fnClear = fnClear
        },
        initLocalSearch(map) {
            var local = new BMap.LocalSearch(map, {
                renderOptions:{map: map}
            });
            this.local = local
        },
        // 驾车导航
        initDriving (map) {
            let self = this
            var driving = new BMap.DrivingRoute(map, { 
                renderOptions: { 
                    map: map, 
                    panel: "r-result",
                    autoViewport: true,
                    enableDragging : true
                },
                // onSearchComplete: self.searchComplete
            });
            this.driving = driving
        },
        searchComplete (res) {
            let self = this
            console.log(res)
            var lng = ""
            var lat = ""
            var arrPois = []
            if (this.driving.getStatus()==BMAP_STATUS_SUCCESS) {
                var plan = res.getPlan(0);
                        var arrPois =[];
                        for(var j=0;j<plan.getNumRoutes();j++){
                            var route = plan.getRoute(j);
                            arrPois= arrPois.concat(route.getPath());
                        }
                        self.map.addOverlay(new BMap.Polyline(arrPois, {strokeColor: '#ff0000'}));
                        self.map.setViewport(arrPois);
            }
        },
        getBoundary(area){  
            let self = this     
            var bdary = new BMap.Boundary();
            bdary.get(area, function(rs){       //获取行政区域
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    console.log('未能获取当前输入行政区域');
                    return ;
                }
                self.map.clearOverlays();        //清除地图覆盖物       
                var pointArray = [];
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
                    self.map.addOverlay(ply);  //添加覆盖物
                    pointArray = pointArray.concat(ply.getPath());
                }    
                self.map.setViewport(pointArray);    //调整视野  
                            
            });   
        },
        // 路书
        luluSu (map) {
            let self =this
            var lushu;
            // 实例化一个驾车导航用来生成路线
            var drv = new BMap.DrivingRoute('北京', {
                onSearchComplete: function(res) {
                    if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
                        var plan = res.getPlan(0);
                        var arrPois =[];
                        for(var j=0;j<plan.getNumRoutes();j++){
                            var route = plan.getRoute(j);
                            arrPois= arrPois.concat(route.getPath());
                        }
                        map.addOverlay(new BMap.Polyline(arrPois, {strokeColor: '#ff0000'}));
                        map.setViewport(arrPois);

                        lushu = new BMapLib.LuShu(map,arrPois,{
                        defaultContent:"第一救援队",//"从天安门到百度大厦"
                        autoView:true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
                        icon  : new BMap.Icon(myCar, new BMap.Size(52,26),{anchor : new BMap.Size(27, 13)}),
                        speed: 4500,
                        enableRotation:true,//是否设置marker随着道路的走向进行旋转
                        landmarkPois: [
                        {lng:116.314782,lat:39.913508,html:'加油站',pauseTime:2},
                        {lng:116.315391,lat:39.964429,html:'高速公路收费<div><img src="//map.baidu.com/img/logo-map.gif"/></div>',pauseTime:3},
                        {lng:116.381476,lat:39.974073,html:'肯德基早餐',pauseTime:2}
                        ]});
                        self.lushu = lushu
                    }
                }
            });
             var start=new BMap.Point(116.404844,39.911836);
            var end=new BMap.Point(116.308102,40.056057);
            drv.search(start, end);
            
        },
        handleSave () {
            let self = this
            if (this.start && this.end) {
                // this.geoc.getPoint(this.start,function(point1){
                //     console.log(point1)
                //     if (point1) {
                //         self.geoc.getPoint(self.end,function(point2){
                //             if (point2) {
                //                 self.driving.search(point1,point2)
                //             }
                //         })
                //     }
                // })
                self.driving.search(this.start,this.end)
            }
        },
        handleLocalSearch () {
            if (this.key) {
                this.local.search(this.key)
                this.getBoundary(this.key)
            }
        },
        G () {
            return document.getElementById(id)
        },
        initGroundOverlay () {
             // 西南角和东北角
            var SW = new BMap.Point(116.29579,39.837146);
            var NE = new BMap.Point(116.475451,39.9764);

            var groundOverlayOptions = {
                opacity: 1,
                displayOnMinLevel: 10,
                displayOnMaxLevel: 14
            }

            // 初始化GroundOverlay
            var groundOverlay = new BMap.GroundOverlay(new BMap.Bounds(SW, NE), groundOverlayOptions);
            groundOverlay.setImageURL(si_huan)
            this.groundOverlay = groundOverlay
        },
        handleAddGroundOverlay () {
            console.log(22)
            this.map.addOverlay(this.groundOverlay);
        },
        handleRemoveGroundOverlay () {
            this.map.removeOverlay(this.groundOverlay);
        },
        handleMenuClick (index) {
            let obj = {
                [index]: !this.activeObj[index],
            }
            this.activeObj = obj
        }
    },
    mounted () {
        this.initMap()
        this.initGlobalMethods()
    }
}
</script>

<style lang="stylus">
    .home
        position relative
    .tool
        display flex
        position absolute
        top 65px
        right 80px
        color #fff
        // background-color #fff
        background-color #000
        .tool-kind
            position relative
            padding 5px 8px
            border 1px solid #333
            cursor pointer
            &:hover .tool-list
                display block
            .tool-list
                position absolute
                left 0
                top 32px
                display none
                padding 5px
                border 1px solid #333
                background-color #000
                width 100%
                .label-title
                    vertical-align 8px
                    padding 0 5px
    .search-wrap
        position absolute
        // left 25px
        left 152px
        top 25px
        z-index 5
        width 420px
        .r-result
            color #ffffff
            border 1px solid
    aside
        position absolute
        top 25px
        left 1px
        width 150px
        max-height 800px
        // border 1px solid #fff
        color #fff
        // background-color #fff
        background-color #000
        .a-title
            position relative
            padding 10px 3px
            .el-icon-arrow-down
                position absolute
                right 10px
                top 12px
        .sub-item-wrap
            overflow hidden
            height 0
            &.active
                height auto
        li.sub-item
            padding 3px
            border-bottom 1px solid
            background-color #000
            cursor pointer
            &:hover
                background-color #666
        img
            width 30px
            height 30px
            vertical-align middle
        .label-name
            margin-left 10px
            vertical-align middle
</style>
<style>
.ball-scale {
    position: absolute;
    z-index: 0;
    top: 0;
    left: 0;
}
[data-loader='ball-scale'] {
    width: 50px;
    height: 50px;
    animation: ball-scale infinite linear .75s;
    border-radius: 100%;
    background-color: #fff;
}
@keyframes ball-scale {
    0% {
        transform: scale(.1);
        opacity: 1;
    }

    100% {
        transform: scale(1);
        opacity: 0;
    }
}
dl,dt,dd,ul,li{
		margin:0;
		padding:0;
		list-style:none;
	}
	dt{
		font-size:14px;
		font-family:"微软雅黑";
		font-weight:bold;
		border-bottom:1px dotted #000;
		padding:5px 0 5px 5px;
		margin:5px 0;
	}
	dd{
		padding:5px 0 0 5px;
	}
	li{
		/* line-height:28px; */
	}
    #r-result,#r-result table{width:100%;}
    #r-result {
        overflow-y: scroll;
        position: absolute;
        top: 184px;
        left: 150px;
        width: 420px;
        z-index: 2;
        max-height: 450px;
    }
</style>